import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Box,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControlLabel,
  Checkbox,
  FormGroup,
  Chip,
  Stack,
  Tooltip
} from '@mui/material'
import AddIcon from '@mui/icons-material/Add'
import EditIcon from '@mui/icons-material/Edit'
import DeleteIcon from '@mui/icons-material/Delete'
import ContentCopyIcon from '@mui/icons-material/ContentCopy'
import ShareIcon from '@mui/icons-material/Share'
import PublicIcon from '@mui/icons-material/Public'
import PersonIcon from '@mui/icons-material/Person'
import { workflows as workflowApi, users as userApi } from '../services/api'

interface Workflow {
  id: number
  name: string
  description: string
  created_at: string
  updated_at: string
  user_id: number
}

interface User {
  id: number
  username: string
  full_name?: string
}

interface WorkflowShare {
  id: number
  workflow_id: number
  user_id?: number
  is_public: boolean
}

const WorkflowList = () => {
  const navigate = useNavigate()
  const [workflows, setWorkflows] = useState<Workflow[]>([])
  const [loading, setLoading] = useState(true)
  const [shareDialogOpen, setShareDialogOpen] = useState(false)
  const [currentWorkflow, setCurrentWorkflow] = useState<Workflow | null>(null)
  const [users, setUsers] = useState<User[]>([])
  const [selectedUsers, setSelectedUsers] = useState<number[]>([])
  const [isPublic, setIsPublic] = useState(false)
  const [currentUser, setCurrentUser] = useState<any>(null)

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        // 从localStorage获取当前用户信息
        const userString = localStorage.getItem('user')
        if (userString) {
          const userData = JSON.parse(userString)
          setCurrentUser(userData)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }

    fetchUserData()
  }, [])

  useEffect(() => {
    const fetchWorkflows = async () => {
      try {
        const response = await workflowApi.list()
        setWorkflows(response.data)
      } catch (error) {
        console.error('获取工作流列表失败:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchWorkflows()
  }, [])

  const handleCreate = () => {
    navigate('/workflows/new')
  }

  const handleEdit = (id: number) => {
    navigate(`/workflows/${id}`)
  }

  const handleDelete = async (id: number) => {
    try {
      await workflowApi.delete(id)
      setWorkflows(workflows.filter(workflow => workflow.id !== id))
    } catch (error) {
      console.error('删除工作流失败:', error)
    }
  }

  const handleCopy = async (id: number) => {
    try {
      const originalWorkflow = workflows.find(workflow => workflow.id === id)
      if (!originalWorkflow) return
      
      const copyData = {
        name: `${originalWorkflow.name} (复制)`,
        description: originalWorkflow.description
      }
      
      const response = await workflowApi.copy(id, copyData)
      const newWorkflow = response.data
      setWorkflows([...workflows, newWorkflow])
    } catch (error) {
      console.error('复制工作流失败:', error)
    }
  }

  const handleShare = async (workflow: Workflow) => {
    setCurrentWorkflow(workflow)
    
    try {
      // 获取所有可以共享的用户
      const usersResponse = await userApi.forSharing()
      setUsers(usersResponse.data)
      
      // 获取当前工作流的共享信息
      const sharesResponse = await workflowApi.getShares(workflow.id)
      const shares = sharesResponse.data
      
      // 设置已选用户和公开状态
      const public_share = shares.find((share: WorkflowShare) => share.is_public)
      setIsPublic(!!public_share)
      
      const user_shares = shares.filter((share: WorkflowShare) => !share.is_public && share.user_id)
      setSelectedUsers(user_shares.map((share: WorkflowShare) => share.user_id as number))
      
      setShareDialogOpen(true)
    } catch (error) {
      console.error('获取共享信息失败:', error)
    }
  }

  const handleSaveShare = async () => {
    if (!currentWorkflow) return

    try {
      const shareData = {
        user_ids: isPublic ? [] : selectedUsers,
        is_public: isPublic
      }
      
      await workflowApi.share(currentWorkflow.id, shareData)
      setShareDialogOpen(false)
    } catch (error) {
      console.error('保存共享设置失败:', error)
    }
  }

  const handleCloseShareDialog = () => {
    setShareDialogOpen(false)
    setSelectedUsers([])
    setIsPublic(false)
    setCurrentWorkflow(null)
  }

  const handleUserSelect = (userId: number) => {
    if (selectedUsers.includes(userId)) {
      setSelectedUsers(selectedUsers.filter(id => id !== userId))
    } else {
      setSelectedUsers([...selectedUsers, userId])
    }
  }

  const handlePublicToggle = (event: React.ChangeEvent<HTMLInputElement>) => {
    setIsPublic(event.target.checked)
  }

  const isOwner = (workflow: Workflow) => {
    return currentUser && workflow.user_id === currentUser.id
  }

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
        <Typography variant="h4">工作流列表</Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={handleCreate}
        >
          新建工作流
        </Button>
      </Box>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>名称</TableCell>
              <TableCell>描述</TableCell>
              <TableCell>所有者</TableCell>
              <TableCell>创建时间</TableCell>
              <TableCell>更新时间</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {workflows.map((workflow) => (
              <TableRow key={workflow.id}>
                <TableCell>
                  <Stack direction="row" spacing={1} alignItems="center">
                    {workflow.name}
                    {!isOwner(workflow) && (
                      <Tooltip title="共享工作流">
                        <Chip 
                          icon={<PublicIcon fontSize="small" />} 
                          size="small" 
                          label="共享" 
                          color="primary" 
                          variant="outlined" 
                        />
                      </Tooltip>
                    )}
                  </Stack>
                </TableCell>
                <TableCell>{workflow.description}</TableCell>
                <TableCell>
                  {isOwner(workflow) ? (
                    <Chip icon={<PersonIcon />} label="我" size="small" />
                  ) : (
                    <Chip label="其他用户" size="small" variant="outlined" />
                  )}
                </TableCell>
                <TableCell>{new Date(workflow.created_at).toLocaleString()}</TableCell>
                <TableCell>{new Date(workflow.updated_at).toLocaleString()}</TableCell>
                <TableCell>
                  <IconButton
                    color="primary"
                    onClick={() => handleEdit(workflow.id)}
                  >
                    <EditIcon />
                  </IconButton>
                  
                  {isOwner(workflow) && (
                    <>
                      <IconButton
                        color="secondary"
                        onClick={() => handleCopy(workflow.id)}
                      >
                        <ContentCopyIcon />
                      </IconButton>
                      <IconButton
                        color="info"
                        onClick={() => handleShare(workflow)}
                      >
                        <ShareIcon />
                      </IconButton>
                      <IconButton
                        color="error"
                        onClick={() => handleDelete(workflow.id)}
                      >
                        <DeleteIcon />
                      </IconButton>
                    </>
                  )}
                  
                  {!isOwner(workflow) && (
                    <IconButton
                      color="secondary"
                      onClick={() => handleCopy(workflow.id)}
                    >
                      <ContentCopyIcon />
                    </IconButton>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 共享对话框 */}
      <Dialog open={shareDialogOpen} onClose={handleCloseShareDialog} maxWidth="sm" fullWidth>
        <DialogTitle>共享工作流</DialogTitle>
        <DialogContent>
          <FormGroup sx={{ mb: 2 }}>
            <FormControlLabel 
              control={<Checkbox checked={isPublic} onChange={handlePublicToggle} />} 
              label="公开给所有用户" 
            />
          </FormGroup>
          
          {!isPublic && users.length > 0 && (
            <Box>
              <Typography variant="subtitle1" sx={{ mb: 1 }}>选择用户:</Typography>
              <FormGroup>
                {users.map(user => (
                  <FormControlLabel
                    key={user.id}
                    control={
                      <Checkbox 
                        checked={selectedUsers.includes(user.id)} 
                        onChange={() => handleUserSelect(user.id)}
                      />
                    }
                    label={user.full_name || user.username}
                  />
                ))}
              </FormGroup>
            </Box>
          )}
          
          {!isPublic && users.length === 0 && (
            <Typography color="textSecondary">没有可供共享的用户</Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseShareDialog}>取消</Button>
          <Button onClick={handleSaveShare} variant="contained" color="primary">
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}

export default WorkflowList 